package kr.co.cherryt.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import kr.co.cherryt.cherryt.R;
import kr.co.cherryt.cherryt.R.layout;
import kr.co.cherryt.cherryt.UpdateChecker;
import kr.co.cherryt.cherryt.UpdateChecker.CheckResultLisnter;
import kr.co.cherryt.common.CC_Log;
import kr.co.cherryt.common.CherrytData;
import kr.co.cherryt.common.Utility;
import kr.co.cherryt.data.parser.AdXmlParser;
import kr.co.cherryt.data.unit.AdInfo;
import kr.co.cherryt.data.unit.UserInfo;
import kr.co.cherryt.parser.xml.XmlItem;
import kr.co.cherryt.parser.xml.XmlManager;
import kr.co.cherryt.parser.xml.XmlManager.XmlResponse;
import kr.co.cherryt.receiver.SmsBroadcastReceiver;
import kr.co.cherryt.util.MemoryStatus;
import kr.co.cherryt.view.AdGallery;
import kr.co.cherryt.view.GalleryListView;
import kr.co.cherryt.view.GalleryNavigator;
import kr.co.cherryt.view.OneFlingGallery;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.SyncStateContract.Constants;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

//hs-TODO// URL 정리 좀 하지;;;
//hs-TODO// sdcard의 저장 경로는 유일할 수 있도록 packageName을 이용하도록 하자. (옵션 값들을 모아두자)
//hs-TODO// WebView 초기화 과정은 별도로 분리하자.
//gsi-TODO// 03-22 15:04:11.425: W/webview(15789): 	at kr.co.cherryt.activity.CherryTActivity$JSInterface.processHTML(CherryTActivity.java:683)
//gsi-TODO// 로그인, 세션에 관한 글 http://catnest.tistory.com/54


public class CherryTActivity extends Activity implements View.OnClickListener {
	
	private TabHost tabHost = null;

	static public Context context;
//	static public boolean chkFlag;
//	static TabHost tabHost;

	String sdcardPath = "/sdcard/gossip/";

	private SharedPreferences preferences;
	SharedPreferences.Editor edit;

	static public boolean bLogin = false;
	static public boolean login;

	private FrameLayout mIntroLayout;
	private LinearLayout mMainLayout;
	private LinearLayout mMainLayoutTop;
	private TextView mNamePoint;

	private FrameLayout mContentLayout;
	private LinearLayout mGalleryLayout;
	private LinearLayout mPoliticsTermsLayout;
	private LinearLayout mPoliticsMainLayout;
	
	private LinearLayout layoutShare;
	private GalleryListView galleryListView;
	
	private static boolean touch=true;	//탭터치 제어변수(프리로딩이 시작되면 False,  종료되면 true)
	

	// 첫 (기업광고) 뷰에서의 세팅. [BEGIN]
	private boolean bEnterpriseAd = true;
	static public boolean bPersonalAd = false;
	private boolean bUccAd = false;
	private boolean bCommunity = false;
	private boolean bGallery = true;
	private boolean bPolitics = false;
	private boolean bWebBlankFirst = true; // 첫 로딩 시 about:blank 페이지 처리
	private boolean bMenuProcessing = false; // 메뉴를 누른 후, 갤러리 등이 처리 중이면 true
	// 첫 (기업광고) 뷰에서의 세팅. [END]
	private boolean bShowMenu = true;
	
	private int nAdSelect = R.id.btnMenu1;
	private RelativeLayout preLoadingView;

	private WebView webView;

	private ValueCallback<Uri> mUploadMessage;

	// CheckBoxPreference cbpUse;

	private Handler mHandler = new Handler();

	static public OneFlingGallery mGallery;
	private GalleryNavigator mNavi;

	private GalleryReadCompletionHandler mGalleryReadCompletionHandler = null;
	private GalleryReadRequestHandler mGalleryReadRequestHandler = null;
	private AdGallery adGallery = null;

	static public int mAdPosition = -1; // 현재 갤러리의 광고 position
	static public int mAdListPosition = 1; // 갤러리 시작 위치
	static public ArrayList<AdInfo> adInfoArray = new ArrayList<AdInfo>();

	final int CALLER_MOVIE = 1;
	final int FILECHOOSER_RESULTCODE = 2;
	final int CALLER_MENU = 3;

	// 갤러리에서 제스쳐 검출
	private GestureDetector mGestureDetector;
	View.OnTouchListener mGestureListener;

	// 사용자 정보 읽어오기
	static public UserInfo userInfo = new UserInfo();

	// 푸쉬
	static public String strRegistrationID = new String("");
	protected static CherryTActivity cherryTActivity;

	// SMS Receiver Intent
	BroadcastReceiver mSmsIntent = null;

	// 상담신청 시 모바일 번호 입력
	//String mMobile = null;
	
	WindowManager manager;
	Display dis;
	int isDisplay = 0;
	DisplayMetrics outMetrics ;
	int displayDpi;
	int androidYSize;
	int androidXSize;
	int selectedTab=0;

	private Handler mHandler1;
	private Runnable mRunnable;
	
	private UpdateChecker m_updateChecker;
	
	private XmlManager xmlManager = null;
	
	// C2DM을 이용한 Action 1번 제한용 boolean 값
	private boolean m_bC2dmAction = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		//startActivity(new Intent(this, IntroActivity.class));

		super.onCreate(savedInstanceState);
		
		dis =  ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
		androidYSize = dis.getHeight();
		androidXSize = dis.getWidth();
		
		if(androidYSize >= 800 && androidYSize < 1024){
			Log.i("test","test");
			setContentView(R.layout.cherryt_activity);// 갤럭시원 (F)WVGA 해상도0
		}
		else if(androidYSize == 1280&& androidXSize ==720)  {
			Log.i("test","test1");
			setContentView(R.layout.layout_1280x720);    // 갤럭시s2 hd 전용 해상도0
		}
		else if(androidYSize ==1280&&androidXSize==800)  {
			Log.i("test","test2");
			setContentView(R.layout.layout_xhdpi_1280x800);    // 갤럭시 노트 전용 해상도0
		}
		else if(androidYSize ==1232)  {
			Log.i("test","test7");
			setContentView(R.layout.layout_sw800dp);    // 갤럭시탭10.1
		}
		else if(androidYSize==1024&&androidXSize==768){
			Log.i("test","test4");
			setContentView(R.layout.layout_1024x768);  //옵티머스 뷰 해상도0
		}
		else if(androidYSize==1024&&androidXSize==600){
			Log.i("test","test6");
			setContentView(R.layout.layout_1024x600);  //갤탭7.0 해상도0
		}
		else if(androidYSize == 480&&androidXSize==320)  {
			Log.i("test","test3");
			setContentView(R.layout.layout_normal);    // 옵티머스원 전용 해상도0
		}
		else{
			Log.i("test","test5");
			setContentView(R.layout.cherryt_activity);  
		}

		preLoadingView = (RelativeLayout) findViewById(R.id.preloading_view);
		initialize();
		

		mIntroLayout = (FrameLayout) findViewById(R.id.introLayout);
		mMainLayout = (LinearLayout) findViewById(R.id.mainLayout);
		mMainLayoutTop = (LinearLayout) findViewById(R.id.mainLayoutTop);
		mNamePoint = (TextView) findViewById(R.id.NamePoint);

		mContentLayout = (FrameLayout) findViewById(R.id.ContentLayout);
		mGalleryLayout = (LinearLayout)findViewById(R.id.galleryLayout);
		mNavi = (GalleryNavigator) findViewById(R.id.navi);
		
		layoutShare = (LinearLayout)findViewById(R.id.layoutShare);
		if (layoutShare == null) {
			CC_Log.info("jin", "layoutShare == null !!!");
		}
		galleryListView = (GalleryListView)findViewById(R.id.galleryListView);
		if (galleryListView == null) {
			CC_Log.info("jin", "galleryListView == null !!!");
		}
	
		
		mPoliticsTermsLayout = (LinearLayout) findViewById(R.id.politicsTermsLayout);
		mPoliticsMainLayout = (LinearLayout) findViewById(R.id.politicsMainLayout);

		context = this;

		// 상담신청 시 사용
//		TelephonyManager tm;
//		tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//		mMobile = tm.getLine1Number();
//
//		// +821077294707의 '+'제거
//		if (mMobile.substring(0, 1).equalsIgnoreCase(new String("+"))) {
//			mMobile = "0" + mMobile.substring(3);
//			try {
//				mMobile = URLEncoder.encode(mMobile, "EUC-KR");
//			} catch (UnsupportedEncodingException e1) {
//				e1.printStackTrace();
//			}
//		}

		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		edit = preferences.edit();

		mGestureDetector = new GestureDetector(this, new MyGestureDetector());
		mGestureListener = new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				return mGestureDetector.onTouchEvent(event);
			}
		};

		// Web 뷰
		
		// 메인 웹 뷰
		webView = new WebView(this);
		webView = (WebView) this.findViewById(R.id.webview);
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setDefaultFontSize(12);
		webView.getSettings().setDomStorageEnabled(true);
		webView.addJavascriptInterface(new JSInterface(), "HTMLOUT");
		webView.requestFocus();
		webView.requestFocusFromTouch();

		webView.setWebChromeClient(new WebChromeClient() {
			// For Android 3.0+
			public void openFileChooser(ValueCallback<Uri> uploadMsg,
					String acceptType) {
				mUploadMessage = uploadMsg;
				Intent i = new Intent(Intent.ACTION_GET_CONTENT);
				i.addCategory(Intent.CATEGORY_OPENABLE);
				i.setType("*/*");
				CherryTActivity.this.startActivityForResult(
						Intent.createChooser(i, "File Chooser"),
						FILECHOOSER_RESULTCODE);
			}

			// For Android < 3.0
			public void openFileChooser(ValueCallback<Uri> uploadMsg) {
				openFileChooser(uploadMsg, "");
			}

			// JavaScript: alert
			public boolean onJsAlert(WebView view, String url, String message,
					final JsResult result) {
				new AlertDialog.Builder(context)
						.setTitle("체리티 알림")
						.setMessage(message)
						.setPositiveButton(android.R.string.ok,
								new AlertDialog.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										result.confirm();
									}
								}).setCancelable(false).create().show();

				return true;
			};
			
			// JavaScript: alert
			public boolean onJsConfirm(WebView view, String url, String message, final android.webkit.JsResult result){
		           new AlertDialog.Builder(view.getContext())
		              .setTitle("체리티 선택")
		              .setMessage(message)
		              .setPositiveButton(android.R.string.ok,
		                    new DialogInterface.OnClickListener() {
		                       public void onClick(DialogInterface dialog, int which) {
		                          result.confirm();
		                       }
		                    })
		              .setNegativeButton(android.R.string.cancel,
		                    new DialogInterface.OnClickListener() {
		                       public void onClick(DialogInterface dialog, int which) {
		                          result.cancel();
		                       }
		                    })
		              .create()
		              .show();
		           return true;
		        };
		});
		
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {

				// Toast.makeText( context, url, Toast.LENGTH_SHORT ).show();

				// 로그인이 되지 않은 상태에서 첫 광고 화면이 뜰 때
				// 사용자 정보를 우선 읽어 온다.
				if (url.equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1")) {
					setWebViewVisibility(
							"http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1",
							View.INVISIBLE);
					webView.loadUrl("http://cherryt.co.kr/ct/?mid=ct_mb_info&version=3");
					bLogin = true;
					return false;
				}
				
				Log.d("cherryt", "should: "+url);

				Uri uri = Uri.parse(url);

				if (url.startsWith("CherryT:") || url.startsWith("cherryt:")) {
					// Toast.makeText( context, url, Toast.LENGTH_LONG ).show();

					// 동영상재생
					if (uri.getQuery().startsWith("play")) {
						// if (uri.getQuery().startsWith("play")) {
						String str = new String();
						str = uri.getFragment();
						// Log.d("cherryt", "fr: " + str);

						Uri uri2 = Uri.parse(str);
						// Log.d("cherryt", "query: " + str);

						Intent intent = new Intent(context,
								AdPlayerActivity.class);
						intent.putExtra("url", uri.getFragment());
						intent.putExtra("control", "no");
						intent.putExtra("title",
								uri2.getQueryParameter("title"));
						intent.putExtra("company", "");
						intent.putExtra("writer",
								uri2.getQueryParameter("writer"));

						startActivityForResult(intent, CALLER_MOVIE);
					}

					else if (uri.getQuery().startsWith("pplaycontrol")) {
						String str = new String();
						str = uri.getFragment();
						// Log.d("cherryt", "fr: " + str);

						Uri uri2 = Uri.parse(str);
						// Log.d("cherryt", "query: " + str);

						Intent intent = new Intent(context,
								UccPlayerActivity.class);
						intent.putExtra("url", uri.getFragment());
						intent.putExtra("control", "yes");
						intent.putExtra("title",
								uri2.getQueryParameter("title"));
						intent.putExtra("company", "");
						intent.putExtra("writer",
								uri2.getQueryParameter("writer"));

						startActivityForResult(intent, CALLER_MOVIE);
					}

					// 동적 광고
					else if (uri.getQuery().startsWith("dynamic")) {
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri
								.parse(uri.getFragment()));
						startActivity(intent);

						//setWebViewVisibility("dynamic", View.VISIBLE);
						mGalleryLayout.setVisibility(View.INVISIBLE);
					}

					// Vibration
					else if (uri.getQuery().startsWith("vibration")) {
						int nMS = 1000;

						String strMS = uri.getFragment();

						if (strMS.length() > 0) {
							nMS = Integer.parseInt(strMS); // 1/1000 초
						}

						Vibrator vibrator = (Vibrator) context
								.getSystemService(Context.VIBRATOR_SERVICE);
						vibrator.vibrate(nMS);
					}

					else if (uri.getQuery().startsWith("gallery"))
					{
						webView.clearHistory();
						setWebViewVisibility("resultCode == 0", View.INVISIBLE);
						mGalleryLayout.setVisibility(View.VISIBLE);
						layoutShare.setVisibility(View.GONE);
						galleryListView.setVisibility(View.VISIBLE);
						
						
						// Log.d("cherryt", "gallery1" );
						//CC_Log.info("jin", "gallery!!!");

						/*if (bEnterpriseAd || bPersonalAd) {
							if (nAdSelect == R.id.btnMenu1) {
								// Log.d("cherryt", "gallery2" );
								adInfoArray = AdXmlParser.GetAdXMLData(
										AdXmlParser.RSS_TYPE_CORPORATE,
										userInfo, mAdListPosition);
							} else if (nAdSelect == R.id.btnMenu2) {
								// Log.d("cherryt", "gallery3" );
								adInfoArray = AdXmlParser.GetAdXMLData(
										AdXmlParser.RSS_TYPE_SHARE, userInfo,
										mAdListPosition);
								
								mNavi.setSize(adInfoArray.size());

								GalleryGetImageThread thread = new GalleryGetImageThread(context, 0);
								thread.setDaemon(true);
								thread.start();
							}
							
							startPreloading();

							
							mGalleryReadCompletionHandler = new GalleryReadCompletionHandler();

							
						}*/
					}

					else if (uri.getQuery().startsWith("settings")){
					     Intent intent = new Intent(context, SettingsActivity.class);
					     startActivity(intent);
					     }
					else if (uri.getQuery().startsWith("app"))
					{
						String str = new String();
						str = uri.getFragment();
						 Log.d("cherryt", "fr: " + str);
						 Log.d("cherryt", "fr: " + uri.getFragment());
						Uri uri2 = Uri.parse(str);
						
						String szPpTitle = uri2.getQueryParameter("pptitle");
						String szPName = uri2.getQueryParameter("pname");
						String szPTitle = uri2.getQueryParameter("ptitle");
						
						CC_Log.info("jin", "pptitle : " + szPpTitle);
						CC_Log.info("jin", "pname : " + szPName);
						CC_Log.info("jin", "ptitle : " + szPTitle);
						CC_Log.info("jin", "szPName.toLowerCase() : " + szPName.toLowerCase());
						
						/*Log.d("cherryt", "fr: " + uri2.getQueryParameter("pptitle"));
						Log.d("cherryt", "fr: " + uri2.getQueryParameter("pname"));
						Log.d("cherryt", "fr: " + uri2.getQueryParameter("ptitle"));*/
						
						 PackageManager pm = getPackageManager(); 
						 try {
							 pm.getApplicationInfo(szPName, PackageManager.GET_META_DATA);
							 //패키지가 있을경우 실행할 내용
							 Toast.makeText(context, szPTitle + " 설치완료 되었습니다.", Toast.LENGTH_SHORT).show();
							 view.loadUrl("http://cherryt.co.kr/ct/index.php?module=portalpoint&title=" + szPpTitle);
						 }
						 catch (NameNotFoundException e)
						 { 
							 //패키지가 없을경우 실행할 내용
							 Toast.makeText(context, szPTitle + " 설치되지 않았습니다.", Toast.LENGTH_SHORT).show();
						 }

					}
					// 상담신청
					else if (uri.getQuery().startsWith("consult"))
					{
						view.loadUrl(uri.getFragment() + "&mobile=010");
						//view.loadUrl(uri.getFragment() + "&mobile=" + mMobile);
						// Log.d("cherryt", "상담: " + uri.getFragment() +
						// "&mobile=" + mMobile );
					}
					return true;
				} else if (url.startsWith("tel")) {
					// Log.d("cherryt", "should: return true");
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(url));
					startActivity(intent);

					return true;
				} else if (url.startsWith("market")) {
					// Log.d("cherryt", "should: return true");
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(url));
					startActivity(intent);
					return true;
				} else if (url.startsWith("vguardcheck")) {
					// Log.d("cherryt", "should: return true");
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(url));
					startActivity(intent);
					return true;
				} else if (url.startsWith("file")) {
					// Log.d("cherryt", "should: return true");
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(url));
					startActivity(intent);
					return true;
				} else if (url.startsWith("kakaolink")) {
					// Log.d("cherryt", "should: return true");
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(url));
					startActivity(intent);
					return true;
				} else if (!url.startsWith("http") && !url.startsWith("https") && userInfo.getRID().length() > 0) {
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
					
					// 쇼핑 -> 신한카드 결재 시에 특정 APP이 없으면 에러 발생
					// 혹시 에러가 발생하면 다음 단계로 자동 이동하도록
					if( intent != null ) {
						try {
							startActivity(intent);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					return true;
				} 				

				// Log.d("cherryt", "should: return false");
				return false;
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				Log.d("cherryt", "onPageStarted: " + url);

				if (!url.equals("about:blank")) {
					// setWebViewVisibility("onPageStart", View.INVISIBLE);
					startPreloading();
				}
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				Log.d("cherryt", "onPageFinished:" + url);

				// 페이지가 시작되고 빈 페이지인 경우의 처리
				if (bWebBlankFirst && url.equals("about:blank")) {
					bWebBlankFirst = false;
					return;
				}

				if (url.equals("about:blank")) {
					if (nAdSelect == R.id.btnMenu9) {
						setWebViewVisibility("about:blank", View.INVISIBLE);

						// String strNextConfirm =
						// preferences.getString("TERMCONFIRM", "NO");
						//
						// Log.d("cherryt", "terms check: " + strNextConfirm );
						//
						// if (strNextConfirm.equals("YES")) {
						// setWebViewVisibility("id == R.id.btnMenu9",
						// View.INVISIBLE);
						// mGalleryLayout.setVisibility(View.INVISIBLE);
						// mPoliticsTermsLayout.setVisibility(View.INVISIBLE);
						// mPoliticsMainLayout.setVisibility(View.VISIBLE);
						// }

						// Log.d("cherryt2", "### onPageFinished:" + bPolitics);
						// Log.d("cherryt2", "mPoliticsMainLayout: "+
						// mPoliticsMainLayout.getVisibility());

						if (bPolitics
								&& mPoliticsMainLayout.getVisibility() == View.INVISIBLE) {
							mPoliticsMainLayout.setVisibility(View.VISIBLE);
						}

						setWebViewVisibility("nAdSelect == R.id.btnMenu9",
								View.INVISIBLE);
					}
					return;
				}

				stopPreloading();

				UpdatePoint();

				// 로그인 정보 얻기
				if (url.equals("http://cherryt.co.kr/ct/?mid=ct_mb_info&version=3")) {
					setWebViewVisibility(
							"http://cherryt.co.kr/ct/?mid=ct_mb_info&version=3",
							View.INVISIBLE);
					webView.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementsByTagName('body')[0].innerHTML);");
					
				}

				// 로그인이 시작되면
				else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&act=dispMemberLoginForm")) {
					
					mGalleryLayout.setVisibility(View.INVISIBLE);
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							ViewGroup.LayoutParams.WRAP_CONTENT,
							ViewGroup.LayoutParams.WRAP_CONTENT);
					mMainLayoutTop.setLayoutParams(layoutParams);
					ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
					mainLeftTitleIconImage.setImageResource(R.drawable.headbar_login);
					findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
					setWebViewVisibility("dispMemberLoginForm", View.INVISIBLE);
					webView.setVisibility(View.VISIBLE);
					//webView.getSettings().getLayoutAlgorithm();
				}
				//회원가입
				else if (webView.getUrl()	.equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&act=dispMemberSignUpForm")) {
					
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							ViewGroup.LayoutParams.WRAP_CONTENT,
							ViewGroup.LayoutParams.WRAP_CONTENT);
					mMainLayoutTop.setLayoutParams(layoutParams);
					ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
					mainLeftTitleIconImage.setImageResource(R.drawable.headbar_join);
					findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
										
				}
				//아이디 찾기
				else if (webView.getUrl()	.equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&mid=id_finder_a")) {
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							ViewGroup.LayoutParams.WRAP_CONTENT,
							ViewGroup.LayoutParams.WRAP_CONTENT);
					mMainLayoutTop.setLayoutParams(layoutParams);
					ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
					mainLeftTitleIconImage.setImageResource(R.drawable.headbar_find_id);
					findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				}
				//비밀번호 찾기
				else if (webView.getUrl()	.equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=0&act=dispMemberFindAccount")) {
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							ViewGroup.LayoutParams.WRAP_CONTENT,
							ViewGroup.LayoutParams.WRAP_CONTENT);
					mMainLayoutTop.setLayoutParams(layoutParams);
					ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
					mainLeftTitleIconImage.setImageResource(R.drawable.headbar_find_fw);
					findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
					}
				//마이페이지 포인트 선물하기
				else if (webView.getUrl().equals("http://cherryt.co.kr/ct/ct_mb_tel")) {
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							ViewGroup.LayoutParams.WRAP_CONTENT,
							ViewGroup.LayoutParams.WRAP_CONTENT);
					mMainLayoutTop.setLayoutParams(layoutParams);
					ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
					mainLeftTitleIconImage.setImageResource(R.drawable.headbar_settings_02);
					findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				}
				//적립금 환급 신청
				else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=ct_reward&act=dispBoardWrite&m=1")) {
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							ViewGroup.LayoutParams.WRAP_CONTENT,
							ViewGroup.LayoutParams.WRAP_CONTENT);
					mMainLayoutTop.setLayoutParams(layoutParams);
					ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
					mainLeftTitleIconImage.setImageResource(R.drawable.headbar_settings_03);
					findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				}
				//쇼핑 내역
				else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=shopxe")) {
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							ViewGroup.LayoutParams.WRAP_CONTENT,
							ViewGroup.LayoutParams.WRAP_CONTENT);
					mMainLayoutTop.setLayoutParams(layoutParams);
					ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
					mainLeftTitleIconImage.setImageResource(R.drawable.headbar_settings_04);
					findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				}
				//이벤트 참여내역
				else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=event_ac")) {
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							ViewGroup.LayoutParams.WRAP_CONTENT,
							ViewGroup.LayoutParams.WRAP_CONTENT);
					mMainLayoutTop.setLayoutParams(layoutParams);
					ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
					mainLeftTitleIconImage.setImageResource(R.drawable.headbar_settings_05);
					findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				}
				//포인트 참여내역
				else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=point_ac")) {
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							ViewGroup.LayoutParams.WRAP_CONTENT,
							ViewGroup.LayoutParams.WRAP_CONTENT);
					mMainLayoutTop.setLayoutParams(layoutParams);
					ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
					mainLeftTitleIconImage.setImageResource(R.drawable.headbar_settings_06);
					findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				}
				//친구에게 알리기
				else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=friend&m=1&set=1")) {
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							ViewGroup.LayoutParams.WRAP_CONTENT,
							ViewGroup.LayoutParams.WRAP_CONTENT);
					mMainLayoutTop.setLayoutParams(layoutParams);
					ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
					mainLeftTitleIconImage.setImageResource(R.drawable.headbar_settings_07);
					findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				}
				//공지사항
				else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=ct_notice")) {
					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							ViewGroup.LayoutParams.WRAP_CONTENT,
							ViewGroup.LayoutParams.WRAP_CONTENT);
					mMainLayoutTop.setLayoutParams(layoutParams);
					ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
					mainLeftTitleIconImage.setImageResource(R.drawable.headbar_settings_08);
					findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				}
				// 로그인
				else if (url
						.equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&act=dispMemberLoginForm")) {
					Log.d("cherryt", "url : #3");
					setWebViewVisibility(
							"http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&act=dispMemberLoginForm",
							View.VISIBLE);
				}

				// 광고
				else if (!bLogin && url.equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1")) {
					webView.invalidate();
					bLogin = true;
				}

				else if (webView.getUrl().equals("http://cherryt.co.kr/ct/")) {
					webView.goBack();
					Toast.makeText(context,"아이디/비밀번호가 일치하지 않습니다.",Toast.LENGTH_LONG).show();
				}

				else if (webView.getUrl().equals(
						"http://cherryt.co.kr/ct/?mid=ct_ad&m=1")) {
					setWebViewVisibility("member login", View.INVISIBLE);
					mStartHandler.sendEmptyMessageDelayed(0, 0);
				}

				// 기업광고 클릭 시 화면 로딩이 완료된 후 표시
				else if (nAdSelect == R.id.btnMenu1) {
					mGalleryLayout.setVisibility(View.INVISIBLE);
					// setWebViewVisibility("nAdSelect == R.id.btnMenu1",
					// View.VISIBLE);
					if (url.contains("mid=m_about")) {
						setWebViewVisibility("mid=m_about", View.VISIBLE);
					}
					if (url.contains("mid=ct_share")) {
						setWebViewVisibility("mid=ct_share", View.VISIBLE);
					}
					
				}

				else if (nAdSelect == R.id.btnMenu5) {
					mGalleryLayout.setVisibility(View.INVISIBLE);
					setWebViewVisibility("nAdSelect == R.id.btnMenu5",
							View.VISIBLE);
				}

				else if (nAdSelect == R.id.btnMenu2) {
					mGalleryLayout.setVisibility(View.INVISIBLE);
					setWebViewVisibility("nAdSelect == R.id.btnMenu2",
							View.VISIBLE);
					if (url.contains("mid=ct_share")) {
					      setWebViewVisibility("mid=ct_share", View.VISIBLE);
					     }
				} else {
					Log.d("cherryt", "## who are you????? ##");
				}

				// Log.d("cherryt", "visible" + webView.getVisibility() );
			}
		});

		webView.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_UP:
					if (!v.hasFocus()) {
						v.requestFocus();
					}
					break;
				}
				return false;
			}
		});


		
		// 갤러리 좌우 버튼
		((Button) findViewById(R.id.btnGalleryLeft)).setOnClickListener(this);
		((Button) findViewById(R.id.btnGalleryRight)).setOnClickListener(this);

		// 약관 동의 버튼
		((Button) findViewById(R.id.btnTermsAgree)).setOnClickListener(this);

		// 광고보기
		((Button) findViewById(R.id.btnAdView)).setOnClickListener(this);
		
		// 메뉴, 설정 버튼
		//((Button) findViewById(R.id.btnMenuTopLeft)).setOnClickListener(this);
		((Button) findViewById(R.id.btnMenu)).setOnClickListener(this);
		((Button) findViewById(R.id.btnMenu10)).setOnClickListener(this);

		// 정치 메인 버튼
		((Button) findViewById(R.id.btnPP01)).setOnClickListener(this);
		((Button) findViewById(R.id.btnPP02)).setOnClickListener(this);
		((Button) findViewById(R.id.btnPP03)).setOnClickListener(this);
		((Button) findViewById(R.id.btnPP04)).setOnClickListener(this);
		((Button) findViewById(R.id.btnPP05)).setOnClickListener(this);
		((Button) findViewById(R.id.btnPP06)).setOnClickListener(this);
		((Button) findViewById(R.id.btnPP07)).setOnClickListener(this);

		Log.d("lifecycle", "1. onCreate");
		
		// 초기화면 공지사항 처리
		String szUrl = CherrytData.getXmlUrl(CherryTActivity.this, "ct_intro_notice.php");
		CC_Log.info("jin", "공지사항 url : " + szUrl);
		
		xmlManager = new XmlManager();
		xmlManager.setNewElementItemList("item_list", "item");
		xmlManager.fillItemArrayAsync(szUrl, m_hIntroNotice, CherryTActivity.this);
	}
	
	private Handler m_hIntroNotice = new Handler() {
		public void handleMessage(Message msg) {
			
			XmlResponse rep = new XmlResponse(msg);
			if(rep.getXmlManager() == xmlManager){
			
				XmlItem item = xmlManager.getXmlItemList();
				//String szResultCode = item.getXmlElementData("resultCode");
				String szNoticeVer = item.getXmlElementData("noticeVer");
				String szNoticeTitles = item.getXmlElementData("titles");
				String szNoticeContent = item.getXmlElementData("content");
				String szNoticeFlag = item.getXmlElementData("flag");
				
				int nNoticeVer = -1;
				if (!Utility.IsEmpty(szNoticeVer)) {
					nNoticeVer = Integer.parseInt(szNoticeVer);
				}
				
				if((CherrytData.getNoticeVer(context) < nNoticeVer) && (!Utility.IsEmpty(szNoticeFlag)) && (szNoticeFlag.equals("Y"))){
					Utility.showAlertWithTitle(context, szNoticeTitles, szNoticeContent);
					CherrytData.setNoticeVer(context, nNoticeVer);
				}
			}
			
		}
		
	};

	// webView로 인해 화면이 하얗게 깜빡이는 듯함. 그래서 화면 조절을 위해 함수로 작성
	private void setWebViewVisibility(String where, int visibility) {
		Log.d("cherryt2", "where: " + where + ":"
				+ (visibility == View.VISIBLE ? "VISIBLE" : "INVISIBLE"));
		webView.setVisibility(visibility);
	}

	protected void onStart() {
		Log.d("lifecycle", "2. onStart");
	
		mSmsIntent = new SmsBroadcastReceiver();
		// SMS 단문 받기 리시버 등록
		registerReceiver(mSmsIntent, new IntentFilter(
				"android.provider.Telephony.SMS_RECEIVED"));

		super.onStart();
	}

	protected void onResume() {
		Log.d("lifecycle", "3. onResume");

		super.onResume();
	}

	protected void onPause() {
		Log.d("lifecycle", "4. onPause");
		super.onPause();
	}

	protected void onStop() {
		Log.d("lifecycle", "5. onStop");

		if (mSmsIntent != null) {
			unregisterReceiver(mSmsIntent);
			mSmsIntent = null;
		}

		super.onStop();
	}

	protected void onRestart() {
		Log.d("lifecycle", "6. onRestart");
		super.onRestart();
	}

	@Override
	public void finish() {
		Log.d("lifecycle", "7. finish");
		super.finish();
	}

	@Override
	public void finishActivity(int requestCode) {
		Log.d("lifecycle", "8. finishActivity");
		super.finishActivity(requestCode);
	}

	@Override
	protected void onDestroy() {
		Log.d("lifecycle", "9. onDestroy");

		super.onDestroy();
	}

	private void initialize() {
		InitializationRunnable init = new InitializationRunnable();
		new Thread(init).start();
	}

	class InitializationRunnable implements Runnable {
		public void run() {
			mStartHandler.sendEmptyMessageDelayed(0, 0);
		}
	}

	public void new_message() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("체리티란 무엇일까요?")
				.setMessage(R.string.new_message)
				.setCancelable(false)
				.setPositiveButton("회원가입/로그인", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				})
				.setNegativeButton("둘러보기",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								mStartHandler.sendEmptyMessageDelayed(2, 10);
							}
						});

		dialog.show();

	}

	//public void alert3G() {
		//AlertDialog.Builder dialog = new AlertDialog.Builder(this);
	//	dialog.setTitle("3G 사용 알림")
		//		.setMessage(
		//				"현재 3G로 체리티의 데이터 통신을 사용하고 있습니다. 3G를 사용하면 통신사에 가입한 요금제에 따라 추가적인 데이터 통화료가 부과됩니다.")
		//		.setCancelable(false)
		//		.setPositiveButton("확인", new DialogInterface.OnClickListener() {
			//		public void onClick(DialogInterface dialog, int id) {
			//			edit.putBoolean("check", true);
				//		edit.commit();
			//		}
			//	})
			//	.setNegativeButton("다음에도 보여주기",
				//		new DialogInterface.OnClickListener() {
						//	public void onClick(DialogInterface dialog, int id) {
						//		edit.putBoolean("check", false);
							//	edit.commit();
							//	Toast.makeText(context,
								//		"다음에 사용할 때 3G 경고를 계속 보여줍니다.",
								//		Toast.LENGTH_LONG).show();
							//	dialog.cancel();
						//	}
					//	});
		//dialog.show();
	//}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		mGestureDetector.onTouchEvent(event);
		return super.dispatchTouchEvent(event);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		mGestureDetector.onTouchEvent(event);
		return super.onTouchEvent(event);
	}

	class MyGestureDetector extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			float x1 = e1.getX();
			float x2 = e2.getX();

			// Log.d("cherryt", "gesture: " + x1 + ":" + x2 );

			// if( webView.getVisibility() == View.INVISIBLE ) {
			// // 뒤로 가기
			// if (x1 < x2) {
			// GoGalleryLeft();
			// }
			//
			// // 앞으로 가기
			// else if (x1 > x2) {
			// GoGalleryRight();
			// }
			// }

			return false;
		}
	}

	public final class JSInterface {
		public JSInterface() {
		}

		@SuppressWarnings("unused")
		public void processHTML(String html) {
			Log.d("cherryt", html);

			String info[] = html.split("<br>");

			Log.d("cherryt", "size: " + info.length );

			if (info.length > 2) {
				if (info[0].trim().contains("아이디")) {
					String tmp[] = info[0].trim().split(":");
					if (tmp.length == 2) { 
						userInfo.setUserID(tmp[1].trim());
						CherrytData.setUserId(CherryTActivity.this, tmp[1].trim());
				
						if (info[1].trim().contains("이름")) {
							String tmp2[] = info[1].trim().split(":");
							if (tmp2.length == 2)
								userInfo.setName(tmp2[1].trim());
						}
					
						if (info[2].trim().contains("등록아이디")) {
							String tmp3[] = info[2].trim().split(":");
		
							if (tmp3.length == 2) {
								if (tmp3[1].trim().length() > 10) {
									userInfo.setRID(tmp3[1].trim());
								}
							}
		
							// 등록된 구글 푸시 ID가 없으면 푸쉬를 구글 서버에 등록하고 등록 ID를 받아온다.
							if (userInfo.getUserID().length() > 0) {
								// 푸쉬 설정
								Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
								registrationIntent.putExtra("app", PendingIntent.getBroadcast(context, 0, new Intent(), 0));
								registrationIntent.putExtra("sender", "ibwjeon@gmail.com");
								startService(registrationIntent);
							}
						}
					}
				}
				
				if (info[3].trim().contains("version")) {
					String tmp[] = info[3].trim().split(":");
					if (tmp.length == 2) {
						String strVersion = context.getString(
								R.string.app_version).trim();
						if (!strVersion.equals(tmp[1].trim())) {

							new AlertDialog.Builder(context)
									.setIcon(
											android.R.drawable.ic_menu_close_clear_cancel)
									.setTitle("업데이트 알림")
									.setMessage(
											"새로운 체리티 앱이 출시되었습니다. 지금 설치하시겠습니까?")
									.setPositiveButton(
											"설치",
											new DialogInterface.OnClickListener() {
												
												public void onClick(
														DialogInterface dialog,
														int which) {
													Intent intent = new Intent(
															Intent.ACTION_VIEW,
															Uri.parse("market://details?id=kr.co.cherryt.cherryt"));
													startActivity(intent);
													finish();
												}
											})
									.setNegativeButton(
											"체리티 종료",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int which) {
													finish();
												}
											}).show();

							return;
						}
					}
				}

				// 로그인이 되어 있다면
				String szUserId = userInfo.getUserID();
				
				if (szUserId.length() > 0 && !szUserId.equals("guest")) {
					// Log.d("cherryt", "userInfo == ok");
					CC_Log.info("jin", "로그인 됨 : " + userInfo.getUserID());
					bLogin = true;
					webView.loadUrl("about:blank");
					mStartHandler.sendEmptyMessageDelayed(2, 10);
				} else {
					CC_Log.info("jin", "로그인 안됨");
					// Log.d("cherryt", "userInfo == 0");
					webView.loadUrl("about:blank");
					// webView.invalidate();
					// 로그인 화면으로 이동
					//mStartHandler.sendEmptyMessageDelayed(1, 10);
					// 바로 광고 화면으로 이동
					
					userInfo.setUserID( "guest" );
					CherrytData.setUserId(CherryTActivity.this, "guest");
					userInfo.setName( "사용자" );
						
					mStartHandler.sendEmptyMessageDelayed(3, 10);
				}
			}
		}

		public void vibration() {
			mHandler.post(new Runnable() {
				public void run() {
					webView.loadUrl("javascript:motioncallback()");
					Vibrator vibrator = (Vibrator) context
							.getSystemService(Context.VIBRATOR_SERVICE);
					vibrator.vibrate(1000);
				}
			});
		}
	}

	Handler mStartHandler = new Handler() {
		public void handleMessage(Message msg) {

			// Log.d( "cherryt", "mSH: " + msg.what );

			if (msg.what == 0) {
				mIntroLayout.setVisibility(View.INVISIBLE);
				mMainLayout.setVisibility(View.VISIBLE);
				webView.loadUrl("http://cherryt.co.kr/ct/?mid=ct_mb_info&version=3");
				
			}

			//  로그인 화면으로 이동
			else if (msg.what == 1) {
				mIntroLayout.setVisibility(View.INVISIBLE);
				mMainLayout.setVisibility(View.VISIBLE);
				webView.loadUrl("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&act=dispMemberLoginForm");
			}

			// 초기 화면으로 이동
			else if (msg.what == 2) {
				
				webView.setVisibility(View.GONE);
				ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
				mainLeftTitleIconImage.setImageResource(R.drawable.title01_icon);
				findViewById(R.id.btnMenu10).setBackgroundResource(R.drawable.btn_mypage);
				if(userInfo.getUserID()=="guest" ){
					login=false;
					findViewById(R.id.btnMenu10).setBackgroundResource(R.drawable.btn_login);
					findViewById(R.id.btnMenu10).setVisibility(View.VISIBLE);
				}
				else{
					login=true;
					findViewById(R.id.btnMenu10).setBackgroundResource(R.drawable.btn_mypage);
					findViewById(R.id.btnMenu10).setVisibility(View.VISIBLE);
				}
				//final TabHost tabHost;
				
				if (tabHost != null) {
					CC_Log.info("jin", "탭 null 아님!!!");
					selectedTab = 0;
					tabHost.getTabWidget().setCurrentTab(selectedTab);
				}
				else {
					
					CC_Log.info("jin", "탭 생성!!!");
					tabHost = (TabHost)findViewById(R.id.tabhost);
					tabHost.setup();
					
					//tabHost = getTabHost();
				
					View tabView =createTabView(this, "");
					View tabView1 = createTabView1(this, "");
					View tabView2 = createTabView2(this, "");
					View tabView3 = createTabView3(this, "");
					
					TabHost.TabSpec tabSpec = tabHost.newTabSpec("Tab").setIndicator(tabView);
					TabHost.TabSpec tabSpec1 = tabHost.newTabSpec("Tab1").setIndicator(tabView1);
					TabHost.TabSpec tabSpec2 = tabHost.newTabSpec("Tab2").setIndicator(tabView2);
					TabHost.TabSpec tabSpec3 = tabHost.newTabSpec("Tab3").setIndicator(tabView3);
	
			        tabSpec.setContent(R.id.galleryLayout);
			        tabSpec1.setContent(R.id.webview);
			        tabSpec2.setContent(R.id.webview);
			        tabSpec3.setContent(R.id.galleryLayout);
				       
			        tabHost.addTab(tabSpec);
			        tabHost.addTab(tabSpec1);
			        tabHost.addTab(tabSpec2);
			        tabHost.addTab(tabSpec3);
			        
			        tabHost.setCurrentTab(0);
				}
				tabHost.setOnTabChangedListener(new OnTabChangeListener(){
	
				        	public void onTabChanged(String TabId) {
							
				        		if(touch){
				        			ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
				        			findViewById(R.id.btnMenu10).setVisibility(View.VISIBLE);
					
				        			if(TabId.equals("Tab")){	//기업광고
				        				selectedTab=0;
				        				webView=(WebView)findViewById(R.id.webview);
				        				mMainLayoutTop.setVisibility(View.VISIBLE);
				        				
				        				mainLeftTitleIconImage.setImageResource(R.drawable.title01_icon);
									
				        				/*findViewById(R.id.btnAdViewText1).setVisibility(View.VISIBLE);
										findViewById(R.id.btnAdViewText2).setVisibility(View.INVISIBLE);
										findViewById(R.id.ad_point).setVisibility(View.VISIBLE);
										((ImageView) findViewById(R.id.plus_a)).setVisibility(View.VISIBLE);
										findViewById(R.id.ad_cate).setVisibility(View.VISIBLE);*/
										
										mPoliticsTermsLayout.setVisibility(View.INVISIBLE);
										setWebViewVisibility("tab click", View.VISIBLE);
									
										/*mainLeftTitleIconImage.setImageResource(R.drawable.title01_icon);
										((ImageView) findViewById(R.id.plus_a))
												.setImageResource(R.drawable.plus_a);*/
										
										bEnterpriseAd = true;
										bGallery = true;
										bMenuProcessing = true;
				
										/*adInfoArray = AdXmlParser.GetAdXMLData(
												AdXmlParser.RSS_TYPE_CORPORATE, userInfo, mAdListPosition);
				
										mNavi.setSize(adInfoArray.size());*/
				
										startPreloading();
										
										mGalleryReadCompletionHandler = new GalleryReadCompletionHandler();
				
										GalleryGetImageThread thread = new GalleryGetImageThread(context, 0);
										thread.setDaemon(true);
										thread.start();
									}
									else if(TabId.equals("Tab1")){	//스토어
										selectedTab=1;
										//webView2.setVisibility(View.GONE);
										mMainLayoutTop.setVisibility(View.VISIBLE);
										mainLeftTitleIconImage.setImageResource(R.drawable.title06_icon);
										setWebViewVisibility("tab1 click", View.VISIBLE);
										webView=(WebView)findViewById(R.id.webview);
										webView.loadUrl("http://cherryt.co.kr/ct/index.php?mid=ct_m_shop&listStyle=list");
									}
									else if(TabId.equals("Tab2")){	//이벤트
										//webView2.setVisibility(View.GONE);
										selectedTab=2;
										mMainLayoutTop.setVisibility(View.VISIBLE);
										mainLeftTitleIconImage.setImageResource(R.drawable.title08_icon);
										setWebViewVisibility("tab2 click", View.VISIBLE);
										Cursor cursor = null;
										bCommunity = true;
										webView=(WebView)findViewById(R.id.webview);
										webView.loadUrl("http://cherryt.co.kr/ct/index.php?m=1&mid=ct_event");
									}
									else if(TabId.equals("Tab3")){	//나눔
										selectedTab=3;
		
										webView=(WebView)findViewById(R.id.webview);
										mMainLayoutTop.setVisibility(View.VISIBLE);
										
										((ImageView) findViewById(R.id.btnAdViewText1))
										.setVisibility(View.INVISIBLE);
										((ImageView) findViewById(R.id.btnAdViewText2))
										.setVisibility(View.VISIBLE);
				
										((ImageView) findViewById(R.id.plus_a)).setVisibility(
												 View.VISIBLE );
										
										setWebViewVisibility("tab3 click", View.INVISIBLE);
				
										mainLeftTitleIconImage.setImageResource(R.drawable.title02_icon);
										((ImageView) findViewById(R.id.plus_a))
												.setImageResource(R.drawable.give_a);
				
										bEnterpriseAd = true;
										bGallery = true;
										bMenuProcessing = true;
				
										mPoliticsTermsLayout.setVisibility(View.GONE);
										((TextView) findViewById(R.id.ad_point))
																		.setVisibility(View.VISIBLE);
										
										adInfoArray = AdXmlParser.GetAdXMLData(AdXmlParser.RSS_TYPE_SHARE,
												userInfo, mAdListPosition);
				
										mNavi.setSize(adInfoArray.size());
				
										startPreloading();
										mGalleryReadCompletionHandler = new GalleryReadCompletionHandler();
				
										GalleryGetImageThread thread = new GalleryGetImageThread(context, 3);
										thread.setDaemon(true);
										thread.start();
									
									}
								}else{	//touch가 false 일때(preLoading이 start상태일때) 
									tabHost.setCurrentTab(selectedTab);	//tab의 현재 선택인덱스를 유지
								}
				        	}
					        });
				
				mIntroLayout.setVisibility(View.INVISIBLE);
				mMainLayout.setVisibility(View.VISIBLE);

				webView.clearHistory();

				// 처음에 mMainLayoutTop의 크기는 0dp 이므로 리니어 크기를 원래크기로 복원
				// 로그인 화면에서 상단 바가 나오는 것을 방지하기 위해서 사용
				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
						ViewGroup.LayoutParams.WRAP_CONTENT,
						ViewGroup.LayoutParams.WRAP_CONTENT);
				mMainLayoutTop.setLayoutParams(layoutParams);

				/*adInfoArray = AdXmlParser.GetAdXMLData(
						AdXmlParser.RSS_TYPE_CORPORATE, userInfo,
						mAdListPosition);

				mNavi.setSize(adInfoArray.size());
				*/
				startPreloading();
				mGalleryReadCompletionHandler = new GalleryReadCompletionHandler();

				// Log.d("cherryt", "thread start 1");
				GalleryGetImageThread thread = new GalleryGetImageThread(context, 0);
				thread.setDaemon(true);
				thread.start();
				// Log.d("cherryt", "thread start 2");

				//if (!preferences.getBoolean("check", false)) {
				//	ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				//	if (connectivityManager.getNetworkInfo(
				//			ConnectivityManager.TYPE_MOBILE).isConnected()) {
				//		alert3G();
				//	}
				//}

				String strUserID = userInfo.getUserID();
				
	//			if( strUserID.equals("guest")) {
		//			new_message();
			//	}
				
				//mStartHandler = null;
			}
			else if (msg.what == 3) {
				mIntroLayout.setVisibility(View.INVISIBLE);
				mMainLayout.setVisibility(View.VISIBLE);
				CC_Log.info("jin", "비로그인 상태임");
				webView.loadUrl("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&act=dispMemberLoginForm");
				new_message();
				
			}
		}
		
		private View createTabView(Handler handler, String tabText) {
			// TODO Auto-generated method stub
			View view = LayoutInflater.from(context).inflate(R.layout.custom_tab, null, false);
			TextView tv = (TextView) view.findViewById(R.id.tabTitleText);
			return view;
		}
		private View createTabView1(Handler handler, String string) {
			// TODO Auto-generated method stub
			View view = LayoutInflater.from(context).inflate(R.layout.custom_tab1, null, false);
			TextView tv = (TextView) view.findViewById(R.id.tabTitleText);
			return view;
		}
		private View createTabView2(Handler handler, String string) {
			// TODO Auto-generated method stub
			View view = LayoutInflater.from(context).inflate(R.layout.custom_tab2, null, false);
			TextView tv = (TextView) view.findViewById(R.id.tabTitleText);
			return view;
		}
		private View createTabView3(Handler handler, String string) {
			// TODO Auto-generated method stub
			View view = LayoutInflater.from(context).inflate(R.layout.custom_tab3, null, false);
			TextView tv = (TextView) view.findViewById(R.id.tabTitleText);
			return view;
		}
	};

	// 갤러리 뷰를 보여준다.
	public class GalleryReadCompletionHandler extends Handler {
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				//CC_Log.info("jin", "msg.what == 0");
				
				if (layoutShare != null) {
					layoutShare.setVisibility(View.GONE);
				}
				
				if (galleryListView != null) {
					galleryListView.setVisibility(View.VISIBLE);
				
					// 기업광고 리스트 연결
					galleryListView.fillListViewInner(userInfo, mAdListPosition);
					
					// c2dm을 이용한 다이렉트 액션 처리
					if (m_bC2dmAction == false) {
						m_bC2dmAction = true;
						
						Intent intent = getIntent();
						String szC2dmMode = intent.getStringExtra("c2dmMode");
						String szC2dmParam = intent.getStringExtra("c2dmParam");
						
						if (!Utility.IsEmpty(szC2dmMode) && !Utility.IsEmpty(szC2dmParam)) {
							directC2dmAction(szC2dmMode, szC2dmParam);
						}
					}
				}
			}
			else if (msg.what == 3) {
				//CC_Log.info("jin", "msg.what == 3");
				
				if (layoutShare != null) {
					layoutShare.setVisibility(View.VISIBLE);
				}
				
				if (galleryListView != null) {
					galleryListView.setVisibility(View.GONE);
				}
			}
			
			Log.d("cherryt", "#########   stopPreloading");
			bMenuProcessing = false;
			stopPreloading();
			UpdatePoint();

			setWebViewVisibility("msg.what == 0", View.INVISIBLE);
			mGalleryLayout.setVisibility(View.VISIBLE);
			
			mPoliticsMainLayout.setVisibility(View.INVISIBLE);
			Log.d("cherryt3", "INVISIBLE 880");
			
			// 광고 갤러리 뷰
			mGallery = (OneFlingGallery) findViewById(R.id.ad_gallery);
			mGallery.setFadingEdgeLength(0);
			mGallery.setAdapter(adGallery);
			mGallery.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView parent, View v,
						int position, long id) {
					String strLink = adInfoArray.get(mAdPosition).getLink();
					webView=(WebView)findViewById(R.id.webview);
					webView.loadUrl(strLink);
				}
			});

			mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int id, long arg3) {
					mNavi.setPosition(id);
					mNavi.invalidate();
				}

				public void onNothingSelected(AdapterView<?> arg0) {

				}
			});
			
			mGalleryReadCompletionHandler = null;
		}
	}

	// 갤러리를 읽어 온다.
	public class GalleryReadRequestHandler extends Handler {
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				if (bEnterpriseAd) {
					if (nAdSelect == R.id.btnMenu1) {
						/*adInfoArray = AdXmlParser.GetAdXMLData(
								AdXmlParser.RSS_TYPE_CORPORATE, userInfo,
								mAdListPosition);*/
					} else if (nAdSelect == R.id.btnMenu3) {
						adInfoArray = AdXmlParser.GetAdXMLData(
								AdXmlParser.RSS_TYPE_SHARE, userInfo,
								mAdListPosition);
						
						mNavi.setSize(adInfoArray.size());
						
						GalleryGetImageThread thread = new GalleryGetImageThread(context, 0);
						thread.setDaemon(true);
						thread.start();
					}
					
					startPreloading();

					mGalleryReadCompletionHandler = new GalleryReadCompletionHandler();
				}
				mGalleryReadRequestHandler = null;
			}
		}
	}
	
	public void startPreloading() {
		touch=false;
		
		preLoadingView.setVisibility(View.VISIBLE);
		findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
		mContentLayout.setVisibility(View.GONE);	

		mRunnable=new Runnable(){
		public void run(){
			if(preLoadingView.getVisibility()==View.VISIBLE){
				
					Toast.makeText(context,
							"인터넷 연결이 원활하지 않습니다\n      잠시후 다시 접속해주세요.",
								Toast.LENGTH_LONG).show();
			}
				}
			};
			mHandler1=new Handler();
			mHandler1.postDelayed(mRunnable, 15000);
				
		Log.d("cherryt", "startPreloading");
	}
	
	public void stopPreloading() {
		touch=true;
		preLoadingView.setVisibility(View.INVISIBLE);
		findViewById(R.id.btnMenu10).setVisibility(View.VISIBLE);
		//if (bLogin) {
			mContentLayout.setVisibility(View.VISIBLE);
		//}
			
			mHandler1.removeCallbacks(mRunnable);
		Log.d("cherryt", "stopPreloading");
	}

	class GalleryGetImageThread extends Thread {
		Context ctx;
		int menuNum = 0;

		GalleryGetImageThread(Context ctx) {
			this.ctx = ctx;
		}
		
		GalleryGetImageThread(Context ctx, int menuNum) {
			this.ctx = ctx;
			this.menuNum = menuNum;
		}

		public void run() {

			// release & allocate
			if (adGallery != null) {
				for (int i = 0; i < 50; i++) {
					if (adGallery.imageArray[i] != null) {
						adGallery.imageArray[i] = null;
					}
				}
				adGallery = null;
			}
			if (adGallery == null) {
				adGallery = new AdGallery(ctx);
			}

			 Log.d("cherryt", "thread "+adInfoArray.size());

			for (int i = 0; i < adInfoArray.size(); i++) {
				adGallery.imageArray[i] = new ImageView(context);

				String url = adInfoArray.get(i).getImage();
				// url =
				// "http://cherryt.co.kr/ct/files/cache/thumbnails/879/001/370x370.crop.jpg";

				// Log.d("cherryt", "image load: "+url);

				// 2틀 이상 지났는지 검사
				// 날짜 형식 : 2011-12-25 12:30:05
				SimpleDateFormat format = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				Date dateTime = null;
				long diffInMs;
				long diffInDay = 100; // 100일 이전으로 기본 설정

				if (!bPersonalAd) {
					try {
						dateTime = format.parse(adInfoArray.get(i).getTime());
					} catch (java.text.ParseException e) {
						e.printStackTrace();
					}

					diffInMs = new Date().getTime() - dateTime.getTime();
					diffInDay = (TimeUnit.MILLISECONDS.toSeconds(diffInMs))
							/ (24 * 3600);
				}

				// Log.d("cherryt", "turl"+url);

				try {
					InputStream is = new URL(url).openStream();
					Bitmap bm = BitmapFactory.decodeStream(is);
					Bitmap bm2 = BitmapFactory.decodeResource(getResources(),
							R.drawable.ad_new);

					// 2일 전이면 NEW 이미지 표시
					if (diffInDay <= 2) {
						Bitmap cs = null;
						int width, height = 0;
						width = bm.getWidth();
						height = bm.getHeight();
						cs = Bitmap.createBitmap(width + 1, height,
								Bitmap.Config.ARGB_8888);
						Canvas comboImage = new Canvas(cs);
						comboImage.drawBitmap(bm, 1f, 0f, null);
						comboImage.drawBitmap(bm2, 0f, 0f, null);

						adGallery.imageArray[i].setImageBitmap(cs);

						bm.recycle();
						bm2.recycle();
					} else {
						adGallery.imageArray[i].setImageBitmap(bm);
					}
				} catch (Exception e) {
				}
				// adGallery.imageArray[i].setAdjustViewBounds(true);
				adGallery.imageArray[i]
						.setLayoutParams(new Gallery.LayoutParams(
								LayoutParams.FILL_PARENT,
								LayoutParams.FILL_PARENT));
				// adGallery.imageArray[i].setScaleType(ImageView.ScaleType.FIT_CENTER);
				adGallery.imageArray[i]
						.setScaleType(ImageView.ScaleType.FIT_XY);
			}

			mGalleryReadCompletionHandler.sendEmptyMessage(menuNum);
		}
	};

	public void onMenuClick(int id) {

		if (bMenuProcessing) {
			Toast.makeText(context, R.string.menu_processing, Toast.LENGTH_LONG)
					.show();
			return;
		}

		UpdatePoint();

		// 웹 뷰에서 뒤로 가기 버튼 클릭 시, 예전 정보로 가지 않도록 하기 위해
		webView.clearHistory();
		webView.loadUrl("about:blank");

		// 광고 관련 변수 초기화
		bEnterpriseAd = false;
		bPersonalAd = false;
		bUccAd = false;
		bCommunity = false;
		bPolitics = false;

		nAdSelect = id;
		
		// 갤러리 화면은 R.id.btnMenu1, R.id.btnMenu3 만 사용한다.
		if (id == R.id.btnMenu3 || id == R.id.btnMenu4 || id == R.id.btnMenu6 ||  id == R.id.btnMenu7 || id == R.id.btnMenu8) {
			setWebViewVisibility("id == R.id.btnMenu3 || id == R.id.btnMenu4 || id == R.id.btnMenu6 ||  id == R.id.btnMenu7 || id == R.id.btnMenu8",
					View.VISIBLE);
			mGalleryLayout.setVisibility(View.INVISIBLE);
			mPoliticsTermsLayout.setVisibility(View.INVISIBLE);
			mPoliticsMainLayout.setVisibility(View.INVISIBLE);
			Log.d("cherryt3", "INVISIBLE 1260");
		}
	}

	// 동영상 광고 보기가 종료 또는 강제 종료된 후 호출
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == CALLER_MOVIE) {

			if (resultCode == 1) {
				// 정상 종료
				setWebViewVisibility("resultCode == 1", View.VISIBLE);
			}

			// 종료 버튼에 의한 강제 종료
			else if (resultCode == 0) {
				// UCC가 아닌 경우에는 갤러리 화면으로 복귀
				if (!bUccAd) {
					webView.clearHistory();
					setWebViewVisibility("resultCode == 0", View.INVISIBLE);
					mGalleryLayout.setVisibility(View.VISIBLE);
					layoutShare.setVisibility(View.GONE);
					galleryListView.setVisibility(View.VISIBLE);
				}
			}
		}

		else if (requestCode == FILECHOOSER_RESULTCODE) {
			if (null == mUploadMessage)
				return;
			Uri result = (data == null || resultCode != RESULT_OK) ? null
					: data.getData();
			mUploadMessage.onReceiveValue(result);
			mUploadMessage = null;
		}

		else if (requestCode == CALLER_MENU) {
			if (resultCode == RESULT_OK) {
				int clickedBtnId = data.getIntExtra("btn_id", View.NO_ID);
				onMenuClick(clickedBtnId);
				
			}
			else {
				mContentLayout.setVisibility(View.VISIBLE);
			}
			
		}
		// 광고 보기 눌렀을 때 Link URL을 Extra로 받아와 로딩한다.
		else if (requestCode == CherrytData.GALLERY_DETAIL_RESULT_CODE) {
			if (resultCode == RESULT_OK) {
				String szLink = data.getStringExtra("szLink");
				webView=(WebView)findViewById(R.id.webview);
				CC_Log.info("jin", "광고 링크 : " + szLink);
				webView.loadUrl(szLink);
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	// 안드로이드 내장 메뉴 버튼 처리
//	public boolean onKeyDown(int keycode, KeyEvent event) {
	//	if (keycode == KeyEvent.KEYCODE_MENU) {
//			if (bLogin) {
//				mContentLayout.setVisibility(View.GONE);
//				Intent intent = new Intent(context, MenuActivity.class);
//				startActivityForResult(intent, CALLER_MENU);
//			}

	//		mContentLayout.setVisibility(View.GONE);
	//		Intent intent = new Intent(context, MenuActivity.class);
	//		startActivityForResult(intent, CALLER_MENU);
	//	}

	//	return super.onKeyDown(keycode, event);
//	}

	private void GoGalleryLeft() {
		int position = mGallery.getSelectedItemPosition();
		if (position > 0)
			mGallery.setSelection(position - 1, true);

		if (position == 0) {
			if (mAdListPosition > 51) {
				mAdListPosition -= (50 + adInfoArray.size());
				mGalleryReadRequestHandler = new GalleryReadRequestHandler();
				mGalleryReadRequestHandler.sendEmptyMessageDelayed(0, 10);
			} else {
				Toast.makeText(context, R.string.alarm_of_firstad,
						Toast.LENGTH_SHORT).show();
				Vibrator vibrator = (Vibrator) context
						.getSystemService(Context.VIBRATOR_SERVICE);
				vibrator.vibrate(100);
			}
		}
	}

	private void GoGalleryRight() {
		int position = mGallery.getSelectedItemPosition();
		if (position < mGallery.getCount() - 1)
			mGallery.setSelection(position + 1, true);

		// 앞으로 가기
		if (position + 1 == adInfoArray.size() && adInfoArray.size() == 50) {
			mAdListPosition += 50;
			mGalleryReadRequestHandler = new GalleryReadRequestHandler();
			mGalleryReadRequestHandler.sendEmptyMessageDelayed(0, 10);
		} else if (position + 1 == adInfoArray.size()) {
			Toast.makeText(context, R.string.alarm_of_lastad,
					Toast.LENGTH_SHORT).show();
			Vibrator vibrator = (Vibrator) context
					.getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(100);
		}
	}

	public void onClick(View v) {

		// 갤러리를 왼쪽으로 이동
		if (v.getId() == R.id.btnGalleryLeft) {
			GoGalleryLeft();
			return;
		}

		// 갤러리를 오른쪽으로 이동
		if (v.getId() == R.id.btnGalleryRight) {
			GoGalleryRight();
			return;
		}

		// 동영상 보러 가기
		if (v.getId() == R.id.btnAdView) {

			String strLink = adInfoArray.get(mAdPosition).getLink();
			webView=(WebView)findViewById(R.id.webview);
			CC_Log.info("jin", "광고 링크 : " + strLink);
			webView.loadUrl(strLink);

			return;
		}
		
		if(login==false){
			webView.loadUrl("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&act=dispMemberLoginForm");
		}
		else if(login==true){
			mMainLayoutTop.setVisibility(View.VISIBLE);
			ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
			mainLeftTitleIconImage.setImageResource(R.drawable.headbar_mypage);
			findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);

			setWebViewVisibility("", View.VISIBLE);
			mPoliticsMainLayout.setVisibility(View.INVISIBLE);
			webView=(WebView)findViewById(R.id.webview);
			webView.loadUrl("http://cherryt.co.kr/ct/index.php?mid=mypage&m=1");
		}
	}
		
	// back button 처리
	@Override
	public void onBackPressed() {
		//super.onBackPressed();
		
		if (webView != null) {
			// 기업광고, 나눔 웹 컨텐츠 주소 가져다가 자르기
			String uurl = new String();
			String ttmp[] = webView.getUrl().split("_srl=");
			if( ttmp.length == 2 )  uurl = ( ttmp[0].trim() );
			//Log.d("cherryt", "uurl: "+uurl);
			
			String adurl = new String();
			String adttmp[] = webView.getUrl().split("ad_image/");
			if( adttmp.length == 2 )  adurl = ( adttmp[0].trim() );
			//Log.d("cherryt", "adurl: "+adurl);
								
		
			Log.d("cherryt", "back? : " + webView.getUrl() + bCommunity);
			//
			// Log.d("cherryt", "visible1:mMainLayout: "+
			// mMainLayout.getVisibility());
			// Log.d("cherryt", "visible2:webView: "+ webView.getVisibility());
			// Log.d("cherryt", "visible3:mPoliticsMainLayout: "+
			// mPoliticsMainLayout.getVisibility());
			// Log.d("cherryt", "visible4:mGalleryLayout: "+
			// mGalleryLayout.getVisibility());

			// 1. 커뮤니티인 경우는 종료 처리
			// 2. 로그인 폼에서는 종료 처리
			// 3. 그 이외의 웹 화면이라면, 뒤로가기
			// 뒤로 간 경우, 더 이상 페이지가 없는 "about:blank"이면 이전 Native Android 화면으로
			
			//갤러리일때 종료
			if (mGalleryLayout.getVisibility() ==View.VISIBLE) {
			     new AlertDialog.Builder(this)
			     .setIcon(android.R.drawable.ic_menu_close_clear_cancel)
			     .setTitle("종료")
			     .setMessage("체리티를 종료하시겠습니까?")
			     .setPositiveButton("종료", 
			       new DialogInterface.OnClickListener() {
			        
			        public void onClick(DialogInterface dialog, int which) {
			         moveTaskToBack(true);           
			         System.exit(0);
			        }
			       })
			     .setNegativeButton("취소", null) 
			     .show();
			    }
			//갤러리 설문조사하고 back버튼 호출시 갤러리 뷰로 이동
			 else if(uurl.equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&document")){
				 mGalleryLayout.setVisibility(View.VISIBLE);
				 layoutShare.setVisibility(View.GONE);
					galleryListView.setVisibility(View.VISIBLE);
				   webView.setVisibility(View.INVISIBLE);
			 }
			
			//갤러리기업광고 친구추천
			 else if(webView.getUrl().equals("http://cherryt.co.kr/ct/?mid=m_about&m=1")) {
				 mGalleryLayout.setVisibility(View.VISIBLE);
				 layoutShare.setVisibility(View.GONE);
					galleryListView.setVisibility(View.VISIBLE);
					webView.setVisibility(View.INVISIBLE);
			 }
			 else if(webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=m_about&document_srl=5285&m=1")) {
				 mGalleryLayout.setVisibility(View.VISIBLE);
				 layoutShare.setVisibility(View.GONE);
					galleryListView.setVisibility(View.VISIBLE);
					webView.setVisibility(View.INVISIBLE);
			 }
			 else if(webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=m_about&document_srl=5293&m=1")) {
				 mGalleryLayout.setVisibility(View.VISIBLE);
				 layoutShare.setVisibility(View.GONE);
					galleryListView.setVisibility(View.VISIBLE);
					webView.setVisibility(View.INVISIBLE);
			 }
			
			  //갤러리 나눔에서 back버튼 호출시 갤러리 뷰로 이동
			   else if(uurl.equals("http://cherryt.co.kr/ct/index.php?mid=ct_share&m=1&document")){
				   mGalleryLayout.setVisibility(View.VISIBLE);
				   layoutShare.setVisibility(View.VISIBLE);
					galleryListView.setVisibility(View.GONE);
			      webView.setVisibility(View.INVISIBLE);
			   }
			//로그인폼
			else if(webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&act=dispMemberLoginForm")) {
				
				new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_menu_close_clear_cancel)
				.setTitle("종료")
				.setMessage("체리티를 종료하시겠습니까?")
				.setPositiveButton("종료", 
						new DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								moveTaskToBack(true);           
								System.exit(0);
							}
						})
				.setNegativeButton("취소", null) 
				.show();
			}
			//회원가입 폼
			else if(webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&act=dispMemberSignUpForm")){
				new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_menu_close_clear_cancel)
				.setMessage("취소하시겠습니까?")
				.setPositiveButton("가입 취소", 
						new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						webView.goBack();	
					}
				})
				.setNegativeButton("취소", null) 
				.show();
			}
			//스토어-쇼핑
			 else if(webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=ct_m_shop&listStyle=list")) {
					
					new AlertDialog.Builder(this)
					.setIcon(android.R.drawable.ic_menu_close_clear_cancel)
					.setTitle("종료")
					.setMessage("체리티를 종료하시겠습니까?")
					.setPositiveButton("종료", 
							new DialogInterface.OnClickListener() {
								
								public void onClick(DialogInterface dialog, int which) {
									moveTaskToBack(true);           
									System.exit(0);
								}
							})
					.setNegativeButton("취소", null) 
					.show();
				}
			//이벤트
			 else if(webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?m=1&mid=ct_event")) {
					
					new AlertDialog.Builder(this)
					.setIcon(android.R.drawable.ic_menu_close_clear_cancel)
					.setTitle("종료")
					.setMessage("체리티를 종료하시겠습니까?")
					.setPositiveButton("종료", 
							new DialogInterface.OnClickListener() {
								
								public void onClick(DialogInterface dialog, int which) {
									moveTaskToBack(true);           
									System.exit(0);
								}
							})
					.setNegativeButton("취소", null) 
					.show();
				}
			 else if(webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&mid=id_finder_a")) {
				 webView.goBack();
				}
			 else if(webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=0&act=dispMemberFindAccount")) {
				 webView.goBack();
				}
			//마이페이지
			 else if(webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=mypage&m=1")) {
				 ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
				 if (selectedTab == 0) {
					 mGalleryLayout.setVisibility(View.VISIBLE);
					 layoutShare.setVisibility(View.GONE);
					galleryListView.setVisibility(View.VISIBLE);
					 webView.setVisibility(View.INVISIBLE);
				 }
				 else if (selectedTab == 3) {
					 mGalleryLayout.setVisibility(View.VISIBLE);
					 layoutShare.setVisibility(View.VISIBLE);
					galleryListView.setVisibility(View.GONE);
					 webView.setVisibility(View.INVISIBLE);
				 }
				 else if(selectedTab==1||selectedTab==2){
					 webView.goBack();
				 }
				 if(selectedTab==0){
					 findViewById(R.id.btnMenu10).setVisibility(View.VISIBLE);
					 mMainLayoutTop.setVisibility(View.VISIBLE);
					 mainLeftTitleIconImage.setImageResource(R.drawable.title01_icon);
				 }
				 else if(selectedTab==1){
					 findViewById(R.id.btnMenu10).setVisibility(View.VISIBLE);
					 mMainLayoutTop.setVisibility(View.VISIBLE);
					 mainLeftTitleIconImage.setImageResource(R.drawable.title06_icon);
				 }
				 else if(selectedTab==2){
					 findViewById(R.id.btnMenu10).setVisibility(View.VISIBLE);
					 mMainLayoutTop.setVisibility(View.VISIBLE);
					 mainLeftTitleIconImage.setImageResource(R.drawable.title08_icon);
				 }
				 else if(selectedTab==3){
					 findViewById(R.id.btnMenu10).setVisibility(View.VISIBLE);
					 mMainLayoutTop.setVisibility(View.VISIBLE);
					 mainLeftTitleIconImage.setImageResource(R.drawable.title02_icon);
				 }	
			 }
			 else if (webView.getUrl().equals("http://cherryt.co.kr/ct/ct_mb_tel")) {
				 ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
				 findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				 mMainLayoutTop.setVisibility(View.VISIBLE);
				 mainLeftTitleIconImage.setImageResource(R.drawable.headbar_mypage);
				 webView.goBack();
			 }
			 else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=ct_reward&act=dispBoardWrite&m=1")) {
				 ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
				 findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				 mMainLayoutTop.setVisibility(View.VISIBLE);
				 mainLeftTitleIconImage.setImageResource(R.drawable.headbar_mypage);
				 webView.goBack();
			 }
			 else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=shopxe")) {
				 ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
				 findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				 mMainLayoutTop.setVisibility(View.VISIBLE);
				 mainLeftTitleIconImage.setImageResource(R.drawable.headbar_mypage);
				 webView.goBack();
			 }
			 else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=event_ac")) {
				 ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
				 findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				 mMainLayoutTop.setVisibility(View.VISIBLE);
				 mainLeftTitleIconImage.setImageResource(R.drawable.headbar_mypage);
				 webView.goBack();
			 }
			 else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=point_ac")) {
				 ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
				 findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				 mMainLayoutTop.setVisibility(View.VISIBLE);
				 mainLeftTitleIconImage.setImageResource(R.drawable.headbar_mypage);
				 webView.goBack();
			 }
			 else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=friend&m=1&set=1")) {
				 ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
				 findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				 mMainLayoutTop.setVisibility(View.VISIBLE);
				 mainLeftTitleIconImage.setImageResource(R.drawable.headbar_mypage);
				 webView.goBack();
			 }
			 else if (webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=ct_notice")) {
				 ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
				 findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				 mMainLayoutTop.setVisibility(View.VISIBLE);
				 mainLeftTitleIconImage.setImageResource(R.drawable.headbar_mypage);
				 webView.goBack();
			 }
			 else if (webView.getUrl().contains("http://cherryt.co.kr/ct/index.php?mid=ct_notice&document_srl")) {
				 findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				 webView.goBack();
			 }
			 else if (webView.getUrl().contains("http://cherryt.co.kr/ct/index.php?mid=myinfo_a")) {
				 ImageView mainLeftTitleIconImage = (ImageView) findViewById(R.id.mainTopTitleIcon);
				 findViewById(R.id.btnMenu10).setVisibility(View.INVISIBLE);
				 mMainLayoutTop.setVisibility(View.VISIBLE);
				 mainLeftTitleIconImage.setImageResource(R.drawable.headbar_mypage);
				 webView.goBack();
			 }
			//이벤트탭에서 mid=event_link일때 이벤트 목록으로 이동
			 else if (selectedTab==2&&webView.getUrl().contains("mid=event_link")) {
				 webView.loadUrl("http://cherryt.co.kr/ct/index.php?m=1&mid=ct_event");
			 }
			//기업광고탭에서 mid=event_link일때 갤러리로 이동
			 else if (selectedTab==0&&webView.getUrl().contains("mid=event_link")) {
				 mGalleryLayout.setVisibility(View.VISIBLE); 
				 layoutShare.setVisibility(View.GONE);
					galleryListView.setVisibility(View.VISIBLE);
				 webView.setVisibility(View.INVISIBLE);
			}
			//기업광고에서 웹뷰일때 갤러리로 이동
			else if (selectedTab==0 && webView.getVisibility() == View.VISIBLE) {
				mGalleryLayout.setVisibility(View.VISIBLE);
				layoutShare.setVisibility(View.GONE);
				galleryListView.setVisibility(View.VISIBLE);
				 webView.setVisibility(View.INVISIBLE);
			}
			else if (selectedTab==3 && webView.getVisibility() == View.VISIBLE) {
				mGalleryLayout.setVisibility(View.VISIBLE);
				layoutShare.setVisibility(View.VISIBLE);
				galleryListView.setVisibility(View.GONE);
				 webView.setVisibility(View.INVISIBLE);
			}
			 else if (webView.getUrl().contains("account_a.php")) {
				 webView.loadUrl("http://cherryt.co.kr/ct/giftishow/");
			 }
			 else if (!webView.getUrl().contains("http://cherryt.co.kr/ct/")) {
				 mGalleryLayout.setVisibility(View.VISIBLE);
				 layoutShare.setVisibility(View.GONE);
					galleryListView.setVisibility(View.VISIBLE);
				 webView.setVisibility(View.INVISIBLE);
				}
	
			 
			 
			 
	/*		 
			else if(uurl.equals("http://cherryt.co.kr/ct/index.php?mid=ct_m_shop&listStyle=list&document_srl=5092")){
				webView.goBack();
			}
			// 쇼핑 backbutton처리
			else if(webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?mid=ct_m_shop&listStyle=list")){
				ShowMenuAnimation();
			 	}
			 // 열린광고 backbutton처리
			else if(webView.getUrl().equals("http://cherryt.co.kr/ct/index.php?m=1&mid=ct_ucc")){
				  ShowMenuAnimation();
			}*/
			else if (!bCommunity
					&& !webView
							.getUrl()
							.equals("http://cherryt.co.kr/ct/index.php?mid=ct_ad&m=1&act=dispMemberLoginForm")
					&& webView.getVisibility() == View.VISIBLE) {
				Log.d("cherryt", "history: " + webView.getUrl());
				webView.goBack();
	
				// 웹뷰 페이지는 블랭크인 경우와 그렇지 않은 경우가 있다
				if (webView.getUrl().equals("about:blank")) {
					Log.d("cherryt", "history blank: " + webView.getUrl()
							+ bPolitics);
					setWebViewVisibility("", View.INVISIBLE);
	
					// 정치 후원하기
					if (bPolitics) {
						mPoliticsMainLayout.setVisibility(View.VISIBLE);
						bPolitics = false;
						return;
					}
					
					mGalleryLayout.setVisibility(View.VISIBLE);
					
					 if (selectedTab == 0) {
						layoutShare.setVisibility(View.GONE);
						galleryListView.setVisibility(View.VISIBLE);
					 }
					 else if (selectedTab == 3) {
						layoutShare.setVisibility(View.VISIBLE);
						galleryListView.setVisibility(View.GONE);
					 }
				}
				return;
			} 
			else {
				webView.goBack();
			}	
		}
	}
/*	public void ShowMenuAnimation()
	{
		mContentLayout.setVisibility(View.GONE);
		Intent intent = new Intent(context, MenuActivity.class);
		startActivityForResult(intent, CALLER_MENU);
	}
*/
	public void UpdatePoint() {

		StringBuilder html = new StringBuilder();

		// HTML을 분석하여 <body> 부근의 포인트를 획득한다.
		try {
			URL url = new URL(
					"http://cherryt.co.kr/ct/index.php?mid=mypoint&m=1&id="
							+ userInfo.getUserID());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			if (conn != null) {
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					BufferedReader br = new BufferedReader(
							new InputStreamReader(conn.getInputStream()));

					for (;;) {
						String line = br.readLine();
						if (line == null)
							break;

						if (line.contains("<body>")) {
							line = br.readLine();

							if (line.trim().length() == 0) {
								line = br.readLine();
								html.append(line.trim());
							} else {
								html.append(line.trim());
							}

							break;
						}
					}

					br.close();
				}
				conn.disconnect();
			}
		} catch (Exception ex) {
			;
		}

		TextView userPoint = (TextView) findViewById(R.id.NamePoint);
		userPoint.setText(userInfo.getName() + "님 " + html + "보유");
		Spannable lspan = (Spannable) userPoint.getText();
		// 이름 또는 아이디의 스팬 설정
		lspan.setSpan(new ForegroundColorSpan(0xffffffff), 0, userInfo
				.getName().length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
		lspan.setSpan(new RelativeSizeSpan(1f), 0, userInfo.getName().length(),
				Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		// 포인트의 스팬 설정
		int n = (userInfo.getName() + "님 ").length();

		lspan.setSpan(new ForegroundColorSpan(Color.rgb(255, 203, 8)), n, n
				+ html.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
		lspan.setSpan(new RelativeSizeSpan(1f), n, n + html.length(),
				Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
	}
	
	protected void directC2dmAction(String mode, String param) {
		if (Utility.IsEmpty(mode) || Utility.IsEmpty(param)) {
			return;
		}
		
		if (mode.equals("M")) {
			setWebViewVisibility("direct Ad", View.VISIBLE);
			mGalleryLayout.setVisibility(View.INVISIBLE);
			CC_Log.info("jin", "다이렉트 광고 링크 : " + param);
			webView.loadUrl(param);
		}
		else if (mode.equals("A")) {
			Intent intent = null;
        	
        	// 앱 설치 여부 체크
        	PackageManager pm = getPackageManager();
        	boolean bInstall = Utility.installAppCheck(pm, param);
        	
        	if (bInstall) {
        		CC_Log.info("jin", "앱 설치됨");
        		intent = new Intent(CherryTActivity.this.getPackageManager().getLaunchIntentForPackage(param));
        		CherryTActivity.this.startActivity(intent);
        	}
        	else {
        		CC_Log.info("jin", "앱 설치 안됨");
        		Utility.showAlert(CherryTActivity.this, "앱이 설치되어 있지 않습니다.");
        	}
		}
	}
}

